# common/core/settings.py

import os
from configparser import ConfigParser
# 异常处理
from django.core.exceptions import ImproperlyConfigured

# 获取项目根目录
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

db_file_name = 'db.ini'

# 默认parser对象
default_parser = ConfigParser()
custom_db_file_path = os.path.join(BASE_DIR, 'common', db_file_name)
default_parser.read(custom_db_file_path)

# 自定义parser对象，当存在与项目根目录同级的db.ini配置文件时有效
custom_db_file_path = os.path.join(os.path.dirname(BASE_DIR), db_file_name)
custom_parser = None
if os.path.exists(custom_db_file_path):
    custom_parser = ConfigParser()
    custom_parser.read(custom_db_file_path)

db_configs = {}
web_config_options = default_parser.options('web')
tlbbdb_config__options = default_parser.options('tlbbdb')
web_configs = {}
for option in web_config_options:
    if custom_parser is not None and custom_parser.has_option('web', option):
        web_configs[option] = custom_parser.get('web', option)
    else:
        web_configs[option] = default_parser.get('web', option)
tlbbdb_configs = {}
for option in tlbbdb_config__options:
    if custom_parser is not None and custom_parser.has_option('tlbbdb', option):
        tlbbdb_configs[option] = custom_parser.get('tlbbdb', option)
    else:
        tlbbdb_configs[option] = default_parser.get('tlbbdb', option)


#
# class ToDict:
#
#     def to_dict(self):
#         result = dict()
#         for key, value in self.__class__.__dict__.items():
#             if not key.startswith('__') and not callable(key):
#                 result[key] = value
#         return result
#
#
class DBSettings:
    class Web:
        db = 'web'
        host = web_configs['host']
        port = int(web_configs['port'])
        username = web_configs['username']
        password = web_configs['password']

    class TlbbDB:
        db = 'tlbbdb'
        host = tlbbdb_configs['host']
        port = int(tlbbdb_configs['port'])
        username = tlbbdb_configs['username']
        password = tlbbdb_configs['password']
